package com.example.backendmanage.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.example.backendmanage.common.AjaxResult;


import com.example.backendmanage.info.MyImage;
import com.example.backendmanage.mapper.MyImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/image")
public class ImageController {
    @Value("${images.upload.path}")
    private String ImageUploadPath;

    @RequestMapping("/checkCode2")
    public AjaxResult checkCode2(){
        LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(183,53);
        System.out.println("验证码已生成"+lineCaptcha.getCode());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        lineCaptcha.write(outputStream);
        byte[] bytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(bytes);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("codeImage", base64Image);
        resultMap.put("codeValue", lineCaptcha.getCode());
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(resultMap);
    }

    @Autowired
    MyImageMapper imageMapper;

    @RequestMapping("/upload")
    public String ImageUpload(@RequestParam MultipartFile multipartFile){
        try {
            String originalFileName=multipartFile.getOriginalFilename();
            //获取文件类型
            String type= FileUtil.extName(originalFileName);
            long fileSize=multipartFile.getSize();
            System.out.println(fileSize);
            byte[] bytes=multipartFile.getBytes();
            String base64Image = Base64.getEncoder().encodeToString(bytes);
            String uuid= IdUtil.fastSimpleUUID();
            MyImage myImage=new MyImage();
            myImage.setName(uuid);
            myImage.setSize(fileSize);
            myImage.setType(type);
            myImage.setBase64Code(base64Image);
            imageMapper.addImage(myImage);
            return base64Image;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
